﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
namespace 语音识别例子
{
	public static class Ex
	{
		public static void SaveLog(this string content, params string[] subcontent)
		{
			Console.WriteLine(content, subcontent);
		}
	}

	/// <summary>
	/// 识别结果
	/// </summary>
	public class RecognizeResult
	{
		/// <summary>
		/// 词语
		/// </summary>
		public string Word;
		/// <summary>
		/// 相似度
		/// </summary>
		public double Confidence;
	}


	/// <summary>
	/// 语音识别
	/// </summary>
	public class RecognizedVoice
	{
		private static RecognizedVoice thisClass = null;
		/// <summary>
		/// 获取实例
		/// </summary>
		/// <returns></returns>
		public static RecognizedVoice GetInstance()
		{
			if (thisClass == null) thisClass = new RecognizedVoice();
			return thisClass;
		}

		private static SpeechRecognitionEngine Engine = null;
		/// <summary>
		/// 单例模式
		/// </summary>
		private RecognizedVoice()
		{
		}

		private static Action<RecognizeResult[]> CallbackFunction = null;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="FunctionName"></param>
		public void SetCallback(Action<RecognizeResult[]> function)
		{
			CallbackFunction = function;
		}

		private void FreeEngine()
		{
			Engine.RecognizeAsyncCancel();
			Engine.RecognizeAsyncStop();
			Engine.UnloadAllGrammars();
			Engine.Dispose();
			Engine = null;
		}

		public void SetWords(params string[] words)
		{
			if (Engine != null) FreeEngine();
			if (words == null) return;
			if (words.Count() <= 0) return;

			Engine = new SpeechRecognitionEngine();
			try
			{
				foreach (var config in SpeechRecognitionEngine.InstalledRecognizers())//获取所有语音引擎  
				{
					if (config.Name.ToUpper().IndexOf("CHINESE") >= 0)
					{
						Engine = new SpeechRecognitionEngine(config);
						continue;
					}
					if (config.Description.ToUpper().IndexOf("CHINESE") >= 0)
					{
						Engine = new SpeechRecognitionEngine(config);
						continue;
					}
				}
			}
			catch (Exception EE)
			{
				EE.Message.SaveLog();
			}
			if (Engine == null)
			{
				"无法加载汉语语音识别引擎!".SaveLog();
				return;
			}

			try
			{
				Engine.SetInputToDefaultAudioDevice();
			}
			catch (Exception EEE)
			{
				"配置麦克风输入失败!{0}".SaveLog(EEE.Message);
				return;
			}
			
			Engine.SpeechRecognized += recognizer_SpeechRRecongized;


			//初始化命令词
			var conmmonds = new Choices();

			//添加命令词
			conmmonds.Add((from word in words select word).ToArray());
			//初始化命令词管理
			var gbuilder = new GrammarBuilder();
			//将命令词添加到管理中
			gbuilder.Append(conmmonds);
			//实例化命令词管理
			var grammar = new Grammar(gbuilder);


			Engine.LoadGrammar(grammar);

			Engine.RecognizeAsync(RecognizeMode.Multiple);
		}

		static RecognizedVoice()
		{

		}

		~RecognizedVoice()
		{
			/*
				FreeEngine();
			// */
		}

		//speechrecognized事件处理
		private static void recognizer_SpeechRRecongized(object sender, SpeechRecognizedEventArgs e)
		{
			CallbackFunction?.Invoke(new RecognizeResult[] { new RecognizeResult() { Word = e.Result.Text, Confidence = e.Result.Confidence } });
		}

	}//End Class
}
